/**
 * 
 */
package cn.com.easy.persistence;

import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.binding.MapperMethod;
import org.apache.ibatis.binding.MapperMethod.ParamMap;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;

import cn.com.easy.utils.DateUtils;

/**
 * @author nibili 2020年4月15日上午6:59:28
 *
 */
@Intercepts({ @Signature(type = Executor.class, method = "update", args = { MappedStatement.class, Object.class }) })
public class MyBatisPlusInterceptor implements Interceptor {
	/** 用户id */
	public static ThreadLocal<Long> userIdThreadLocal = new ThreadLocal<Long>();
	/** 用户名称 */
	public static ThreadLocal<String> userNameThreadLocal = new ThreadLocal<String>();

	@Override
	public Object intercept(Invocation invocation) throws Throwable {
		Object[] args = invocation.getArgs();
		MappedStatement ms = (MappedStatement) args[0];
		if (ms.getSqlCommandType() == SqlCommandType.UPDATE) {
			@SuppressWarnings("unchecked")
			MapperMethod.ParamMap<Object> parameter = (ParamMap<Object>) args[1];
			if (parameter != null) {
				Object object = parameter.get("param1");
				if (object instanceof BaseMyBatisPlusEntity) {
					BaseMyBatisPlusEntity baseEntity = (BaseMyBatisPlusEntity) object;
					Date date = DateUtils.getCurrentDateTime();
					baseEntity.setLastModifyTime(date);
					if (StringUtils.isNotBlank(userNameThreadLocal.get()) == true) {
						baseEntity.setCreateBy(userNameThreadLocal.get());
					}
				}
			}
		} else if (ms.getSqlCommandType() == SqlCommandType.INSERT) {
			Object object = args[1];
			if (object instanceof BaseMyBatisPlusEntity) {
				BaseMyBatisPlusEntity baseEntity = (BaseMyBatisPlusEntity) object;
				Date date = DateUtils.getCurrentDateTime();
				baseEntity.setCreateTime(date);
				baseEntity.setLastModifyTime(date);
				if (StringUtils.isNotBlank(userNameThreadLocal.get()) == true) {
					baseEntity.setCreateBy(userNameThreadLocal.get());
				}
				if (userIdThreadLocal.get() != null) {
					baseEntity.setCreateById(userIdThreadLocal.get());
				}
			}
		}
		return invocation.proceed();
	}

}
